<template>
    <div class="style4" >
        <el-container class="style1" direction="horizontal">            
            <el-main>
                
                <!-- <el-input type="file" ref="fileSelect" id="fileSelect" @change="getFilePath(this)" style="disabled:none" />  -->
                <el-upload 
                    action = "http://127.0.0.1:9900/fileUpload"
                    ref="fileSelect"                           
                    :auto-upload="false"
                    :on-change="getFilePath"
                    :on-success="uploadSuccess"
                    name="imgFile"
                    accept="image/*"   id="fileSelect" >
                <el-button type="primary">选择文件</el-button>   
                </el-upload>
            </el-main>
            <el-main><el-button @click="fileSave()">保存图片</el-button></el-main>
            <el-main><el-button @click="restore()">重&emsp;&emsp;&emsp;&emsp;置</el-button></el-main>
            <!-- <el-main><el-button>图片识别</el-button></el-main> -->
            <el-main></el-main>
            <el-main></el-main>
            <el-main></el-main>
            <el-main></el-main>
        </el-container>
        <el-container class="style3">
            <el-aside class="style2"  width="160px">
                <el-menu :default-openeds="['1']">
                    <el-submenu index="1">
                        <template slot="title">ImageEnhance</template>
                            <el-menu-item-group>
                                <el-menu-item index="1-1" @click="imgEnahnce(1)">AutoEnhance1</el-menu-item>
                                <el-menu-item index="1-2" @click="imgEnahnce(2)">AutoEnhance2</el-menu-item>
                                <!-- <el-menu-item index="1-3" @click="imgEnahnce(3)">AutoEnhance3</el-menu-item> -->
                            </el-menu-item-group>
                    </el-submenu>
                    <el-submenu index="2">
                         <template slot="title">Adjust</template>
                            <el-menu-item-group>
                                <el-menu-item index="2-1" @click="RecognitionRegionDetectEvent()">RecRegionDetect</el-menu-item>
                                <el-menu-item index="2-2" @click="correctImageEvent()">CorrectImage</el-menu-item>
                            </el-menu-item-group>
                    </el-submenu>
                    <el-submenu index="3">
                         <template slot="title">Rotate</template>
                            <el-menu-item-group>
                                <el-menu-item index="3-1" @click="turnLeftEvent()">turnLeft</el-menu-item>
                                <el-menu-item index="3-2" @click="turnRightEvent()">turnRight</el-menu-item>
                            </el-menu-item-group>
                    </el-submenu>
                    <el-submenu index="4">
                         <template slot="title">ImageRec</template>
                            <el-menu-item-group>
                                <el-menu-item index="4-1" @click="FileUploadEvent()">FileUpload</el-menu-item>
                                <el-menu-item index="4-2" @click="OffLineRecEvent()">OffLineRec</el-menu-item>
                                <el-menu-item index="4-3" @click="OnLineRecEvent()">OnLineRec</el-menu-item>
                            </el-menu-item-group>
                    </el-submenu>
                </el-menu>

                <!-- <el-button @click="imgTest">图像增强</el-button>
                <el-button>图像矫正</el-button> -->
            </el-aside>
            <el-main class="style5" id="showContainer">
                <canvas id="img"></canvas>
            </el-main>
        </el-container>
    </div>     
</template>
 
<script>
import {Loading} from "element-ui";
import {extractRealImage, obejctRegionDetect, adjustLight, obejecRegionHighLight, imageShow, correctImage,
turnLeft, turnRight, imageZoom, autoEnhance1, autoEnhance2, autoEnhance3} from "@/utils/image";
import {imageRecognition} from "@/api/log";
export default {
    name: "app-main-imgProcess",
    data(){
       return {
            "imgPath":"./static/test02.jpg",
            "nx":-1,
            "ny":-1,
            "nw":-1,
            "nh":-1,
            "realImage":null,
            "lowLightImage":null,
            "points":null,
            "selectPointIndex":-1,
            "isDrawing": false,
            "direction":0,
            "oriImg":null,
            "scale":1.0,
            "imgUrl":null,
       }
    },
    methods:{
        loadImg(){
            const _this = this;
            let img = new Image();
            let imgContainer = document.getElementById("showContainer");
            let imgCanvas = document.getElementById("img");
            img.src = _this.imgPath;
            img.onload = function(){
                const w = imgContainer.offsetWidth;
                const h = imgContainer.offsetHeight;
                const iw = img.width;
                const ih = img.height;
                const screenScale = h/w;
                const imgScale = ih/iw;
                 
                if(imgScale > screenScale) {
                    _this.nh = h;
                    _this.nw = Math.round(h/imgScale);
                    _this.nx = Math.round((w-_this.nw)/2);
                    _this.ny = 0;
                    _this.scale = h/ih;
                }else{
                    _this.nx = 0;
                    _this.nw = w;
                    _this.nh = Math.round(w*imgScale);
                    _this.ny = Math.round((h-_this.nh)/2);
                    _this.scale = w/iw;
                }
                // console.log(h, w, ih, iw)
                // console.log( _this.nx,_this.ny, _this.nw, _this.nh)
                let ctx = imgCanvas.getContext("2d");
                imgCanvas.width = w;
                imgCanvas.height = h;
                ctx.drawImage(img, 0, 0, img.width, img.height, _this.nx, _this.ny, _this.nw, _this.nh);
                //_this.objectRegionShow();
                _this.oriImg = cv.imread(img);
            }
        },
        selectFile(){
            document.getElementById("fileSelect").click();
        },
        getFilePath(f, fs){
            var url;
            if(URL.createObjectURL != undefined){
                url = URL.createObjectURL(f.raw)
                this.imgPath = url;
                this.loadImg();
            }
        },
        objectRegionShow(isExtract=true){
            if(isExtract){
                this.realImage = extractRealImage("img", this.nx, this.ny, this.nw, this.nh);
            }
            this.points = obejctRegionDetect(this.realImage);
            this.lowLightImage = adjustLight(this.realImage);
            let newImage = obejecRegionHighLight(this.realImage, this.lowLightImage, this.points)
            this.draw(newImage);
            newImage.delete();
        },
        imgEnahnce(idx){
            let newImg;
            if(idx==1){
                newImg = autoEnhance1(this.oriImg);
                
            }else if(idx==2){
                newImg = autoEnhance3(this.oriImg);
            }
            let zoomInfo = imageZoom(newImg, this.nw+2*this.nx, this.nh+2*this.ny);
            let zoomImage = zoomInfo[0];
            this.nw = zoomImage.cols;
            this.nh = zoomImage.rows;
            this.nx = zoomInfo[1];
            this.ny = zoomInfo[2];
            this.realImage.delete();
            this.realImage = zoomImage;
            this.oriImg.delete();
            this.oriImg = newImg;
            this.objectRegionShow(false);
        },
        correctImageEvent(){
            let newImage = correctImage(this.oriImg, this.points, this.scale);
            let zoomInfo = imageZoom(newImage, this.nw+2*this.nx, this.nh+2*this.ny);
            let zoomImage = zoomInfo[0];
            this.nw = zoomImage.cols;
            this.nh = zoomImage.rows;
            this.nx = zoomInfo[1];
            this.ny = zoomInfo[2];
            this.realImage.delete();
            this.realImage = zoomImage;
            this.draw(zoomImage, false, false);
            this.oriImg.delete();
            this.oriImg = newImage;
            //newImage.delete();
            
        },
        RecognitionRegionDetectEvent(){
            this.objectRegionShow();
        },
        draw(newImage, modify=false, drawLine=true){
            if(!this.isDrawing){
                this.isDrawing = true;
                if(!modify){
                    imageShow(newImage, this.points, this.nx, this.ny, "img", drawLine);
                }else{
                    let imgContainer = document.getElementById("showContainer");
                    const w = imgContainer.offsetWidth;
                    const h = imgContainer.offsetHeight;
                    const iw = newImage.cols;
                    const ih = newImage.rows;
                    let ox = Math.round((w-iw)/2);
                    let oy = Math.round((h-ih)/2);
                    imageShow(newImage, this.points, ox, oy, "img", drawLine);  
                }  
                this.isDrawing = false;
            } 
        },
        addCanvasEvent(){
            const _this = this;
            let canvasElement = document.getElementById("img");
            canvasElement.onmousedown = function(e){
                let x = e.pageX - this.offsetLeft - _this.nx;
                let y = e.pageY - this.offsetTop - _this.ny;
                let maxOffset = 50;
                let minDistance = 100000;
                // console.log("click:", x, y);
                if(x<0 || x>_this.nw || y<0 || y>_this.nh || _this.points == null){
                    console.log(x, y, "is invaild!");
                }else{
                    for(var i=0;i<_this.points.length;i++){
                        let d = Math.sqrt(Math.pow(x-_this.points[i][0], 2)+Math.pow(y-_this.points[i][1], 2));
                        if(d<minDistance && d<maxOffset){
                            minDistance = d;
                            _this.selectPointIndex = i;
                        }
                    }
                }
            }
            canvasElement.onmouseup = function(e){
                if(_this.selectPointIndex>-1){
                    _this.selectPointIndex = -1;
                }
            }
            canvasElement.onmousemove = function(e){
                let x = e.pageX - this.offsetLeft-_this.nx;
                let y = e.pageY - this.offsetTop-_this.ny;
                if(_this.selectPointIndex>-1){
                    if(x<0){
                        x = 0;
                    }
                    if(x>_this.nw){
                        x = _this.nw;
                    }
                    if(y<0){
                        y = 0;
                    }
                    if(y>_this.nh){
                        y = _this.nh;
                    }
                    _this.points.splice(_this.selectPointIndex, 1, [x, y]);
                    let newImage = obejecRegionHighLight(_this.realImage, _this.lowLightImage, _this.points)
                    _this.draw(newImage);
                    newImage.delete();
                }
            }
        },
        turnLeftEvent(){
            // 待优化， 旋转次数过多导致图像模糊
            let newImage = turnLeft(this.realImage);
            let roateInfo= imageZoom(newImage, this.nw+2*this.nx, this.nh+2*this.ny);
            let roateImage = roateInfo[0];
            this.nw = roateImage.cols;
            this.nh = roateImage.rows;
            this.nx = roateInfo[1];
            this.ny = roateInfo[2];
            this.draw(roateImage, false, false);
            this.realImage.delete();
            this.realImage = roateImage;
            newImage.delete();
        },
        turnRightEvent(){
            let newImage = turnRight(this.realImage);
            let roateInfo= imageZoom(newImage, this.nw+2*this.nx, this.nh+2*this.ny);
            let roateImage = roateInfo[0];
            this.nw = roateImage.cols;
            this.nh = roateImage.rows;
            this.nx = roateInfo[1];
            this.ny = roateInfo[2];
            this.draw(newImage, false, false);
            this.realImage.delete();
            this.realImage = roateImage;
            newImage.delete();
        },
        fileSave(){
            let newCanvas = document.createElement("canvas");
            cv.imshow(newCanvas, this.oriImg);
            const data = newCanvas.toDataURL("image/png");
            const link = document.createElement('a');
            link.href =  data;
            link.download = 'temp.png';
            link.click();
            link.remove();
            newCanvas.remove();
        },
        restore(){
            this.loadImg();
        },
        OnLineRecEvent(){
            if(this.imgUrl != null){
                let jsonData = {"imgUrl": this.imgUrl,
                "onLine": true
                }
                imageRecognition(jsonData).then(function(resp){  
                    console.log(resp)
                }).catch(function(err){
                    console.log(err);
                });
            }else{
                console.log("请选择文件！")
            }
        },
        OffLineRecEvent(){
            if(this.imgUrl != null){
                let jsonData = {"imgUrl": this.imgUrl,
                "onLine": false
                }
                imageRecognition(jsonData).then(function(resp){  
                    console.log(resp)
                }).catch(function(err){
                    console.log(err);
                });
            }else{
                console.log("请选择文件！")
            }
        },
        FileUploadEvent(){
            // console.log("on call FileUploadEvent!");
            this.$refs.fileSelect.submit();
        },
        uploadSuccess(response, file, fileList){
            this.imgUrl = response.img_url;
            console.log("img url:", this.imgUrl);
        }
    },
    mounted(){
        this.addCanvasEvent();
        this.loadImg(); 
    },

}
</script>
<style>
    .style1 {
        background-color: #b0bce4;
        color: #333;
        text-align: center;
        height: 10%;
        line-height: 100px;
    }

    .style2 {
        background-color: #ffffff;
        color: #333;
        text-align: center;
        line-height: 60px;
    }

    .style3 {
        height: 90%;
    }

    .style4 {
        height: 100%;
    }

    .style5 {
        background-color: #f0f0f0;
    }

    .style6{
        height: 200px;
    }
  
</style>